importScripts("./constant.js");

/**
 * @description: 消息监听
 * @return {*}
 */
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
  const { type, tabId } = message;
  switch (type) {
    case "authority":
      await setPopupFn("../popup.html");
      sendResponse(true);
      break;
      case "options":
        await setPopupFn("../html/options.html", true);
        sendResponse(true);
        break;
    case "looping":
      await setPopupFn("../startLoop.html");
      sendResponse(true);
      break;
      case "stopLoop":
        await setPopupFn("../stopLoop.html");
        sendResponse(true);
        break;
        case "notAllowedLoop":
        await setPopupFn("../notAllowedLoop.html");
        sendResponse(true);
        break;
  }
});

/**
 * @description: 设置popup
 * @return {*}
 */
function setPopupFn(popupPath, flag) {
  return new Promise((resolve) => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      let tabId = tabs.length ? tabs[0].id : null;
      let iconPath = '../asset/logo/icon_128x128.png'
      if(flag){
        iconPath = '../asset/logo/icon_default_128x128.png'
      }else{
        iconPath = '../asset/logo/icon_128x128.png'
      }
      chrome.action.setIcon({
        tabId: tabId,
        path: iconPath,
      });
      chrome.action
        .setPopup({
          tabId: tabId,
          popup: popupPath,
        })
        .then((res) => resolve(res));
    });
  });
}

chrome.history.onVisited.addListener((item) => {

  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, (tabs) => {
      let message = {type: 'init'}
      chrome.tabs.sendMessage(tabs[0].id, message, res => {
          console.log(res)
      })
  })

})